import logging
import os
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path

LOG_LEVEL = os.getenv("HITSZ_ARCHIVES_MANAGEMENT_LOG_LEVEL", "INFO")
LOG_FILE = Path(os.getenv("HITSZ_ARCHIVES_MANAGEMENT_LOG_FILE", "app.log"))
LOG_DIR = Path(os.getenv("HITSZ_ARCHIVES_MANAGEMENT_LOG_DIR", "logs"))

LOG_DIR.mkdir(exist_ok=True)


def setup_logger():
    logger = logging.getLogger("src")
    if logger.hasHandlers():
        logger.info("Logger already has handlers, not setting up again")
        return logger

    # 使用 getLevelNamesMapping() 获取日志级别
    log_level_mapping = logging.getLevelNamesMapping()
    log_level = log_level_mapping.get(LOG_LEVEL.upper(), logging.INFO)
    logger.setLevel(log_level)

    log_file = LOG_DIR / LOG_FILE
    # 使用 TimedRotatingFileHandler 实现日志轮转
    file_handler = TimedRotatingFileHandler(
        log_file,
        when="D",  # 按天轮转
        interval=1,  # 每 1 天轮转一次
        backupCount=30,  # 最多保留 30 个备份，即 30 天的日志
        encoding="utf-8",
    )
    formatter = logging.Formatter(
        "%(asctime)s [%(levelname)s] %(filename)s: %(message)s"
    )
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)

    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)

    return logger
